<template>
  <div class="page">
    <!--<div style="min-height:900px">-->
    <!-- <div class="top">
			<div style="float:left;"><span @click="goBack" class="goback">设备管理</span>　|　<span>编辑网关设备</span></div>
			<el-button type="primary" size="small" id="goback" @click="goBack">返回</el-button>
		</div> -->
    <el-form :model="form" block id="addform">
      <el-form-item required label="项目名称:" :label-width="formLabelWidth">
        <el-select v-model="form.product_id" placeholder="选择项目" class="inpu" @change="getDevice(form.product_id)">
          <el-option v-for="item in products" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select><br>
        <!-- <el-cascader
					class="inpu"
					v-model="form.product_id"
					:options="products"
					:props="{ checkStrictly:true,expandTrigger:'hover',emitPath:false}">
				</el-cascader><br> -->
        <span class="tip">如果没有选择项，请先添加项目，否则设备无法添加！</span>
        <!-- <el-input v-model="form.name" auto-complete="off" class="inpu" style="transform: translateX(-0.8rem);" placeholder="输入项目名称"></el-input> -->
      </el-form-item>
      <!-- <el-form-item v-if="grade<=2" label="项目名称:" :label-width="formLabelWidth">
				<el-input v-model="form.product_name" placeholder="所属项目" readonly class="inpu"></el-input><br>
			</el-form-item><br> -->
      <el-form-item required label="设备名称:" :label-width="formLabelWidth" class="formline">
        <el-input v-model="form.equip_name" class="inpu" placeholder="请输入设备名称" spellcheck="false"></el-input><br>
        <!-- <span class="tip">名称必须是中，英文字母，数字，下划线或者破折号的组合</span> -->
      </el-form-item>
      <!-- <el-form-item required label="设备编码:" :label-width="formLabelWidth" class="formline">
				<el-input v-model="form.equip_code" class="inpu" placeholder="请输入设备编码" spellcheck="false" disabled @input="toUpper(form.equip_code)"></el-input><br>
			</el-form-item> -->
      <el-form-item required label="设备编码:" :label-width="formLabelWidth" class="formline">
        <el-input v-model="form.equip_code" class="inpu" placeholder="请输入设备编码" spellcheck="false"></el-input><br>
      </el-form-item>
      <!-- <el-form-item label="版本选择:" class="formline" required :label-width="formLabelWidth">
				<el-select v-model="form.version" placeholder="版本选择" class="inpu" style="width:2.5rem;">
					<el-option v-for="item in versions" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-form-item> -->
      <el-form-item label="联网方式:" class="formline" required :label-width="formLabelWidth">
        <el-select v-model="form.network_way" placeholder="联网方式" class="inpu" style="width:2.5rem;">
          <el-option v-for="item in netTypes" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="应用场景:" class="formline" :label-width="formLabelWidth">
        <el-select v-model="form.app_scene" placeholder="应用场景" :disabled="form.run_mode==2" class="inpu"
          style="width:2.5rem;">
          <el-option v-for="item in scenes" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备图片:" :label-width="formLabelWidth" class="formline2">
        <div class="oldimg">
          <img src="#" id="thumb" class="thumb" />
          <input type="file" id="addid" @change="addUpload" alt="" />
        </div>
        <span class="tip">点击图片可更换</span>
      </el-form-item>
      <!-- <el-form-item label="启用状态:" :label-width="formLabelWidth" class="formline" style="margin-top:-0.5rem;">
        <el-switch v-model="form.equip_state" :width="stateWidth" class="demo"
          style="display:inline-block;vertical-align:top;" active-color="#13ce66" inactive-color="#ccc" active-text="启用"
          inactive-text="禁用" :active-value="one" :inactive-value="zero">
        </el-switch>
      </el-form-item> -->
      <el-form-item label="启用状态:" :label-width="formLabelWidth" class="formline" style="margin-top:-0.5rem;">
        <el-radio-group v-model="form.equip_state">
          <el-radio :label="1" style="font-size:0.3rem;">启用</el-radio>
          <el-radio :label="0" style="font-size:0.3rem;">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="设备排序:" class="formline" :label-width="formLabelWidth">
        <el-input v-model="form.list_order" auto-complete="off" class="inpu" style="width:2.5rem;"
          spellcheck="false"></el-input><br>
        <span class="tip">请输入自然数(0,1,2,3,...),默认以添加的先后顺序排序</span>
      </el-form-item>
      <el-form-item style="margin-left:0.7rem;">
        <el-button type="success" @click="modifyDevice" size="small">保存</el-button>
      </el-form-item>
    </el-form>
    <el-form :model="mapForm" inline id="r_addform">
      <el-form-item label="设备地址:" :label-width="formLabelWidth">
        <el-input v-model="mapForm.address" placeholder="请输入设备地址" class="inpu" spellcheck="false" style="width:11.1rem;"
          @change="isRepeatAddress(mapForm.address)"></el-input></br>
        <span class="tip2"
          style="margin-top:0.2rem">建议点击地图修改定位(可缩放或移动地图);如果要手动输入地址后获取坐标,请至少包含"**省**市"的信息(省会或直辖市可至少有"**市");请确保地址和坐标相互匹配;</span>
      </el-form-item><br>
      <el-form-item label="设备坐标:" :label-width="formLabelWidth" class="formline">
        <el-input v-model="mapForm.lng" class="inpu" placeholder="设备地址经度" spellcheck="false"></el-input>
        <el-input v-model="mapForm.lat" class="inpu" placeholder="设备地址纬度" spellcheck="false"></el-input>
        <el-button size="small" type="primary" style="margin-left:0.5rem;" v-if="mapForm.address"
          @click="getPoint">获取坐标</el-button>
        <!-- 地图控件 -->
        <div id="editMap" ref="editMap"></div>
        <!-- <button class="mapbtn" @click="FullScreen">全屏地图</button> -->
        <!-- <span>提示:点击地图空白处可进入全屏模式，按“esc”键退出全屏！</span> -->
        <!-- 地图结束 -->
      </el-form-item>
    </el-form>
    <!-- <div class="dialog-footer" >
			<el-button type="success" @click="modifyDevice" size="small">保存</el-button>
		</div> -->
  </div>
</template>

<script>
  import AMap from "AMap";
  export default {
    name: 'editDevice',
    data() {
      return {
        // grade: localStorage.getItem("grade"),
        products: [],
        one: 1,
        zero: 0,
        formLabelWidth2: '80px',
        formLabelWidth: '110px',
        baseurl: this.$baseurl,
        icon: "https://gou-bin.oss-cn-beijing.aliyuncs.com/yunken/local.png",
        nowCity: '',
        map: null,
        marker: null,
        stateWidth: 60,
        ws: null,
        id: '',
        devid: '',
        showNew: false,
        oldlook: true,
        uplook: true,
        poi: null,
        point: {
          lat: 34.3440789219,
          lng: 108.9465065501
        },
        netTypes: [{
          value: 1,
          label: '4G'
        }, {
          value: 2,
          label: 'Wifi'
        }, {
          value: 3,
          label: '网口'
        }, ],
        versions: [{
            value: 3,
            label: 'YK5.3'
          },
          {
            value: 4,
            label: 'YK5.4'
          }

        ],
        form: {
          product_id: '',
          thumb: '',
          id: 0,
          version: 3,
          // slave_type:1,
          list_order: 50,
          network_way: 1,
          app_scene: 1,
          //report_interval:60,
          //template_id:0,
          equip_name: '',
          equip_code: '',
          type: 1,
          //run_mode:1,
          equip_state: 1

        },
        scenes: [{
            value: 1,
            label: '通用'
          },
          {
            value: 2,
            label: '水利'
          },
          {
             value:5,
             label:'MQTT遥测'
          }
          // {
          //    value:3,
          //    label:'私有协议-A'
          // }
        ],
        mapForm: {
          address: '',
          lat: '',
          lng: ''
        },
        runModes: [{
            value: 1,
            label: '边缘采集'
          },
          {
            value: 2,
            label: '数据透传'
          }
        ],
        value: '',
        addresses: [],
        options: []

      }
    },
    created() {
      this.id = localStorage.getItem('editDeviceId');
      var that = this;
      this.$http({
        method: 'post',
        url: 'api/equip/info',
        data: {
          "id": that.id

        }
      }).then(res => {
        if (res && res.data.result == "success") {
          for (var key in this.form) {
            this.form[key] = res.data.data[key];
          }
          this.getProduct();
          this.mapForm.address = res.data.data.geo_name;
          this.mapForm.lng = res.data.data.geo_coord ? res.data.data.geo_coord[0] : '';
          this.mapForm.lat = res.data.data.geo_coord ? res.data.data.geo_coord[1] : '';
          this.point.lng = res.data.data.geo_coord ? res.data.data.geo_coord[0] : 108.9465065501;
          this.point.lat = res.data.data.geo_coord ? res.data.data.geo_coord[1] : 34.3440789219;
          this.form.thumb = this.baseurl + res.data.data.thumb;
          //this.form.product_id = res.data.data.product_id;
          if (res.data.data.thumb) {
            document.getElementById("thumb").src = this.form.thumb;
          } else {
            document.getElementById("thumb").src = "../../static/noimg.png";
          }

        }

      }).catch(error => {
        console.log(error)
      });

    },
    mounted() {
      var that = this;
      setTimeout(function() {
        that.showMap("editMap");

      }, 1000)
    },
    methods: {
      getProduct() {
        var that = this;
        this.$http({
          method: 'post',
          url: '/api/product/tree',
          data: {}
        }).then(res => {
          if (res && res.data.result == "success") {
            this.products = res.data.data;
            //console.log(res.data.data);

          }
          //console.log("charu")
        }).catch(error => {

          console.log(error);
        });
      },

      // getDevice(id) {
      //     var that = this;
      // 	this.addresses = [];
      //     this.$http({
      //         method: 'post',
      //         url: 'api/equip/all',
      //         data: {
      //             'product_id': id
      //         }
      //     }).then(res => {
      //         if (res && res.data.result == "success") {
      //             if (res.data.data.length) {
      //                 for (var i = 0, len = res.data.data.length; i < len; i++) {
      //                     var address = {
      //                         value: res.data.data[i].equip_name,
      //                         label: res.data.data[i].geo_name,
      // 						id:res.data.data[i].id
      //                     }
      //                     this.addresses.push(address);
      //                 }
      // 			}
      //         }
      //     }).catch(error => {
      //         console.log(error);
      //     });
      // },

      changeMode(mode) {
        if (mode == 2) {
          this.form.app_scene = 1;
        }
      },

      toUpper(code) {
        this.form.equip_code = code.toUpperCase();
      },

      isRepeatAddress(address) {
        if (!this.addresses.length || !address) {
          return false
        };
        for (let i = 0, len = this.addresses.length; i < len; i++) {
          if ((this.addresses[i].id != this.form.id) && (this.addresses[i].label == address)) {
            this.$message({
              type: 'info',
              dangerouslyUseHTMLString: true,
              message: '<p>提示：当前地址与原有设备<span style="color:red">' + this.addresses[i].value +
                '</span>的地址完全重复，在设备地图上会形成遮挡，</br>建议你可以通过地址轻微错位或修改设备名称长度来解决，也可以忽略不处理！</p>',
              center: true,
              showClose: true,
              duration: 10000,
              offset: 300
            })
            break;
          }
        }
      },

      goBack() {
        this.$router.go(-1);
        this.mapForm.lng = "";
        this.mapForm.lat = "";
      },
      addUpload() {
        var that = this;
        var fileLen = document.getElementById('addid').files;
        this.ws = fileLen[0];
        var reads = new FileReader();
        reads.readAsDataURL(this.ws);
        reads.onload = function(e) {
          document.getElementById('thumb').src = this.result;
        }

        //console.log(this.ws);
      },
      modifyDevice() {
        var that = this;
        delete that.form.thumb;
        var upform = new FormData();
        for (var key in this.form) {
          upform.append(key, that.form[key]);
        }
        upform.append("image", that.ws);
        //upform.append("slave_type", that.form.slave_type);
        upform.append("geo_coord", JSON.stringify([that.mapForm.lng, that.mapForm.lat]));
        upform.append("geo_name", that.mapForm.address);
        this.$http({
          method: 'post',
          url: 'api/equip/update',
          data: upform

        }).then(res => {
          if (res && res.data.result == "success") {

            this.$message({
              message: '恭喜，修改设备成功!',
              type: 'success',
              center: true
            });
            this.$router.go(-1);

          }
        }).catch(error => {
          console.log(error)
        });
      },

      getPoint() {
        var that = this;
        if (this.mapForm.address) {
          this.mapForm.lng = '';
          this.mapForm.lat = '';
          var markers = [];
          if (that.marker) {
            markers.push(that.marker);
          }
          that.map.remove(markers);
          that.map.plugin('AMap.Geocoder', function() {
            var geocoder = new AMap.Geocoder({
              city: "全国",
            }); //城市设为北京，默认：“全国”
            geocoder.getLocation(that.mapForm.address, function(status, result) {
              if (status === 'complete' && result.geocodes.length) {
                var lnglat = result.geocodes[0].location;
                //console.log(lnglat);
                //document.getElementById('lnglat').value = lnglat;
                that.mapForm.lng = lnglat.lng;
                that.mapForm.lat = lnglat.lat;
                that.marker = new AMap.Marker({
                  icon: that.icon,
                  position: [that.mapForm.lng, that.mapForm.lat],
                  offset: new AMap.Pixel(-16, -16)
                });
                //that.marker.setPosition(lnglat);
                that.map.add(that.marker);
                that.map.setFitView(that.marker);
              } else {
                that.$message({
                  message: '当前的输入地址无法获取坐标，你可以重新输入或点击地图获取!',
                  type: 'error',
                  center: true
                });
              }
            });
          });

        } else {
          this.$message({
            message: '地址不能为空，请输入!',
            type: 'error',
            center: true
          });
        }
      },

      // onComplete(res) {
      //     //console.log(res);
      // },
      // onError(error) {
      //     //console.log(error);
      // },
      showMap(idstr) {
        var that = this;
        that.map = new AMap.Map(idstr, {
          resizeEnable: true
        });
        //that.map.plugin('AMap.Geolocation', function() {
        // var geolocation = new AMap.Geolocation({
        //     enableHighAccuracy:true, //是否使用高精度定位，默认:true
        //     timeout: 10000, //超过10秒后停止定位，默认：无穷大
        //     maximumAge: 0, //定位结果缓存0毫秒，默认：0
        //     convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
        //     showButton: false, //显示定位按钮，默认：true
        //     //buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
        //     //buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        //     //showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
        //     //showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
        //     panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
        //     zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        // });
        AMap.plugin([
          'AMap.ToolBar',
          'AMap.Scale'
        ], function() {
          // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
          that.map.addControl(new AMap.ToolBar());

          // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
          that.map.addControl(new AMap.Scale());
          // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
          //that.map.addControl(new AMap.OverView({isOpen:true}));
          // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
          //that.map.addControl(new AMap.MapType());
          // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
          // that.map.addControl(new AMap.Geolocation());
        });
        //that.map.addControl(geolocation);
        //这里不用获取当前位置
        //geolocation.getCurrentPosition();
        // AMap.event.addListener(geolocation, 'complete', that.onComplete); //返回定位信息
        // AMap.event.addListener(geolocation, 'error', that.onError); //返回定位出错信息
        that.marker = new AMap.Marker({
          icon: that.icon,
          position: [that.point.lng, that.point.lat],
          offset: new AMap.Pixel(-16, -16)
        });
        that.marker.setMap(that.map);
        that.map.setZoomAndCenter(10, [that.point.lng, that.point.lat]);
        that.map.on('click', function(e) {
          var markers = [];
          if (that.marker) {
            markers.push(that.marker);
          }
          that.map.remove(markers);
          that.point.lng = e.lnglat.lng;
          that.point.lat = e.lnglat.lat;
          that.mapForm.lng = e.lnglat.lng;
          that.mapForm.lat = e.lnglat.lat;

          that.marker = new AMap.Marker({
            icon: that.icon,
            position: [that.point.lng, that.point.lat],
            offset: new AMap.Pixel(-16, -16)
          });
          that.marker.setMap(that.map);
          AMap.service('AMap.Geocoder', function() { // 回调函数
            var geocoder = new AMap.Geocoder({
              radius: 2000, //逆地理编码时，以给定坐标为中心点半径范围，单位：米，取值0-3000，默认1000
              extensions: "all" //base，返回基本地址信息，all，返回所有地址信息
            });
            geocoder.getAddress([that.point.lng, that.point.lat], function(status, result) {
              if (status === 'complete' && result.info === 'OK') {
                // console.log(result.regeocode.formattedAddress);
                that.mapForm.address = result.regeocode.formattedAddress;
                that.isRepeatAddress(that.mapForm.address);
              } else {
                that.mapForm.address = "获取地理位置失败"
              }
            });
          });
        });
        //});
      }

    }
  }
</script>

<style scoped>
  @media all and (max-width:1600px) {
    .formline {
      margin-top: -0.4rem !important;
    }
  }

  .inpu /deep/ .el-input__inner {
    padding-left: 4px;
  }

  #addform {
    position: relative;
    float: left;
    text-align: left;
    margin-top: 0.3rem;
    width: 34%;
    /* height: 11.2rem; */
    /* border:1px solid red; */
    line-height: 0.6rem;
    z-index: 10;
  }

  #r_addform {
    position: relative;
    line-height: 0.6rem;
    float: left;
    margin-top: 0.3rem;
    text-align: left;
    width: 65%;
    z-index: 10;
    /* border:1px solid red; */
  }

  .inpu {
    width: 5.5rem;
  }

  .tip,
  .tip2 {
    display: inline-block;
    color: #FF5722;
    font-size: 0.25rem;
    line-height: 0.35rem;
    transform: translateY(-0.1rem);
  }

  #editMap {
    margin-top: 0.2rem;
    width: 16rem;
    height: 10rem;
    border: 1px solid #ccc;
  }

  #addid {
    width: 1.5rem;
    height: 1.5rem;
    /* border:1px solid red; */
    overflow: hidden;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 11;
    opacity: 0;
  }

  .oldimg {
    width: 1.5rem;
    height: 1.5rem;
    cursor: pointer;
    border: 1px solid #ccc;
  }

  .thumb {
    width: 1.5rem;
    height: 1.5rem;
  }

  .page:after {
    content: '.';
    display: block;
    height: 0;
    overflow: hidden;
    clear: both;
  }

  .formline {
    margin-top: -0.3rem;
  }

  .formline2 {
    margin-top: -0.2rem;
  }

  .tip2 {
    width: 16rem;
  }
</style>
